﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using TcpServer.Global;


namespace TcpServer.ThreadManage
{
    class MyThread1
    {
        private AutoResetEvent ExitEvent;
        public Thread ThreadHandle;
        private int WaitTime;

        public MyThread1(int time)
        {
            ExitEvent = new AutoResetEvent(false);
            WaitTime = time;
            ThreadHandle = new Thread(new ThreadStart(ThreadProcess));

        }

        public void RunThread()
        {

            ThreadHandle.IsBackground = true;
            ThreadHandle.Start();


        }

        public void StopThread()
        {
            ExitEvent.Set();
            ThreadHandle.Abort();
            ThreadHandle.Join();

        }

        public void ThreadProcess()
        {
            int WriteTimes = 0;

            while (true)
            {
                Console.WriteLine("main local is " + Program.local.ToString());
                Console.WriteLine("do some thing times=" + WriteTimes.ToString()+" "+ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                WriteTimes++;
                Console.WriteLine("MyThread1 内查看 线程状态:" + Thread.CurrentThread.ThreadState.ToString());

                Console.WriteLine("thread global value is " + GlobalClass.g_Count1.ToString());
                GlobalClass.g_Count1++;
                Console.WriteLine("thread global value is " + GlobalClass.g_Count1.ToString());

                if (ExitEvent.WaitOne(WaitTime))
                {
                    
                    break;
                }
                Console.WriteLine("运行完了"+ WriteTimes.ToString() + "次 WaitTime" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            }
            Console.WriteLine("exit Thread1");
        }

    }
}
